import { Inject, Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { loginDto } from './dto/login.dto';
import { firstValueFrom } from 'rxjs';
import { Prisma } from '@prisma/client';
import { PrismaService } from 'src/prisma/prisma.service';
import { randomNumber } from 'src/utils';

@Injectable()
export class UserService {
  constructor(
    private readonly httpService: HttpService, // 确保正确注入
  ) {}

  @Inject(PrismaService)
  private prisma: PrismaService;

  async login(loginDto: loginDto) {
    try {
      const response = await firstValueFrom(
        this.httpService.get(
          `https://api.weixin.qq.com/sns/jscode2session?appid=wx7b0263ff090d1245&secret=ebdd58079af360c1104188cf5bedc3ef&js_code=${loginDto.wxCode}&grant_type=authorization_code`,
        ),
      );
      // 查看数据库是否存在该用户
      const user = await this.prisma.user.findFirst({
        where: {
          weixin_openid: response.data.openid,
        },
      });

      if (!user) {
        // 如果不存在，创建新用户
        const newUser = await this.prisma.user.create({
          data: {
            username: `微信用户_${randomNumber()}`,
            weixin_openid: response.data.openid,
            session_key: response.data.session_key,
          },
        });

        return newUser;
      } else {
        // 如果存在，更新用户信息
        return user;
      }
    } catch (error) {
      // 处理错误
      throw new Error(error);
    }
  }
}
